#!/bin/bash

call_service()
{
    local service_file_path="${1}"
    local service_state="${2}"

    if [ -x "${service_file_path}" ]
    then
        # Executable bit set (chmod +x), call service directly
        "${service_file_path}" "${service_state}" &
    else
        # Executable bit not set, call service via bash interpeter
        bash "${service_file_path}" "${service_state}" &
    fi
}

is_valid_service_name() {
    local LC_ALL=C
    [[ "${1}" =~ ^[_[:alpha:]][_[:alpha:][:digit:]]*$ ]]
}

process_services() {
    local service_type="${1}"
    local service_dir="${2}"
    local service_state="${3}"
    local BASE_SERVICE SERVICE SRVVAR BASE_SERVICE_SUGGEST

        while read SERVICE
        do
            BASE_SERVICE=${SERVICE##*/}
            if is_valid_service_name "${BASE_SERVICE}"
            then
                SRVVAR=__SERVICE__${BASE_SERVICE}
                if test "${!SRVVAR}" = 1; then
                    call_service "${SERVICE}" "${service_state}"
                    echo "${service_type} Service: ${BASE_SERVICE} -> service is enabled [ok]"
                else
                    echo "${service_type} Service: ${BASE_SERVICE} -> service is disabled [ok]"
                fi
            else
                BASE_SERVICE_SUGGEST=$(echo "$BASE_SERVICE" | sed -e 's/[^_A-Za-z0-9]//g' -e 's/^[0-9]*//')
                echo "${service_type} Service: $BASE_SERVICE -> invalid service name, suggest rename service file to: '$BASE_SERVICE_SUGGEST' [failed]"
            fi
        done < <(find -L "${service_dir}" -type f)
}

# custom.sh : deprecated in v43
# mv custom.sh to servicedir, only once. If service is already present then ignore whole action
if [[ -f /userdata/system/custom.sh && ! -f /userdata/system/services/custom_service ]]; then
    [[ -d /userdata/system/services ]] || mkdir /userdata/system/services
    mv /userdata/system/custom.sh /userdata/system/services/custom_service
    batocera-services enable custom_service
fi

enabled_services="$(/usr/bin/batocera-settings-get system.services)"

if test -n "${enabled_services}"
then
    for SERVICE in ${enabled_services}
    do
        export __SERVICE__${SERVICE}=1
    done
fi

# user services
process_services User /userdata/system/services "${1}"

# system user services
process_services System /usr/share/batocera/services "${1}"

# wait for spawned scripts to finish on stop condition, after this shutdown can happen
test "${1}" = "stop" && wait
